package com.unittec.zk.provider.log.service;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy;
import ch.qos.logback.core.util.FileSize;
import ch.qos.logback.core.util.OptionHelper;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

//暂时将所有的业务服务的日志都统一存放在文件中，后续要将日志数据存放到kafaka或者redis，以支持
//日志服务可以集群部署，并支持日志的搜索功能
public class LoggerBuilder {

    private static final Map<String, Logger> CONTAINER = new HashMap<>();

    @SuppressWarnings("unchecked")
    public static Logger getLogger(String name) {
        Logger logger = CONTAINER.get(name);
        if(logger != null) {
            return logger;
        }
        synchronized (LoggerBuilder.class) {
            logger = CONTAINER.get(name);
            if(logger != null) {
                return logger;
            }
            logger = build(name);
            CONTAINER.put(name,logger);
        }
        return logger;
    }

    @SuppressWarnings("unchecked")
    private static Logger build(String name) {
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        Logger logger = context.getLogger("FILE-" + name);
        logger.setAdditive(false);
        RollingFileAppender appender = new RollingFileAppender();
        appender.setContext(context);
        appender.setName("FILE-" + name);
        appender.setFile(OptionHelper.substVars("${log.path}/" + name + ".log",context));
        appender.setAppend(true);
        appender.setPrudent(false);
        SizeAndTimeBasedRollingPolicy policy = new SizeAndTimeBasedRollingPolicy();
        String fp = OptionHelper.substVars("${log.path}/" + name + ".log.%d{yyyy-MM-dd}.%i",context);

        policy.setMaxFileSize(FileSize.valueOf("128MB"));
        policy.setFileNamePattern(fp);
        policy.setMaxHistory(7);
        policy.setTotalSizeCap(FileSize.valueOf("2GB"));
        policy.setParent(appender);
        policy.setContext(context);
        policy.start();

        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        encoder.setContext(context);
        encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} - %msg%n");
        encoder.start();

        appender.setRollingPolicy(policy);
        appender.setEncoder(encoder);
        appender.start();
        logger.addAppender(appender);
        return logger;
    }


    public static void main(String[] args) {
        Logger log = LoggerBuilder.getLogger("test");

        log.debug("debug");
        log.info("info");
        log.warn("warn");
        log.error("error");
    }
}
